TypeScript v4.5
2021/11/17
The Awaited Type and Promise Improvements
従来は、
targetに対するpolyfill感覚でlibを指定していた
これはlibの指定を見て、この辺のやつを自動で読み込んでいた 以下2つの問題がある
libのversion指定ができない
そのため、TypeScriptをupgradeすると、勝手にlibのversionも上がる
例えば、domは頻繁に更新されているため、ぶっ壊れる可能性がある
dependenciesとの組み合わせが困難になることがある
dependenciesの1つがdomに依存していると、domの指定が強制される
v 4.5で、このlibをoverrideする方法が提供された
例えば、libにhogeが指定された場合、
まず最初にnode_modules/@typescript/lib-hoge/を探しに行く
その次に、hoge.es2015.d.tsなどが探される
従来は、問答無用でhoge.es2015.d.tsなどが読み込まれていた
dependenciesに追記することで、この指定ができる
code:package.json
{
"dependencies": {
"@typescript/lib-dom": "npm:@types/web"
}
}
この仕組みにより以下のことができるようになった
libのversionを固定できる
libを自分好みに入れ替えることができる
標準libraryを上書きで他のものに変えられる
Types for the DOM and most web-related APIs
Template String Types as Discriminants
template litearal typesでguardできる
code:ts
export interface Success {
type: ${string}Success;
body: string;
}
export interface Error {
type: ${string}Error;
message: string;
}
export function handler(r: Success | Error) {
if (r.type === "HttpSuccess") {
let token = r.body; // v4.4だとSuccessに絞り込まれていないのでerror
}
}
tsconfigのmoduleにes2022が指定できるようになった
top-level awaitとか使える
Tail-Recursion Elimination on Conditional Types
Conditional Typesで定義する際に、末尾再帰で書くと、ネストを深くできる
Disabling Import Elision
一見未使用に見える宣言を、削除しないようにする
type Modifiers on Import Names
code:after.ts
import { Foo1, type Foo2 } from "foo";
Private Field Presence Checks
private property #hogeの存在チェック
#hoge in objectという式を評価できるようになった
code:ts
class Person {
constructor(name: string) {
this.#name = name;
}
equals(other: unknown) {
return (
other != null &&
typeof other === 'object' &&
this.#name === other.#name
);
}
}
class Person2 {
constructor(name: string) {
this.#name = name;
}
}
console.log(new Person("hoge").equals(new Person("hoge"))); // true
console.log(new Person("hoge").equals(new Person2("hoge"))); // false
①の部分は、
「#nameを持っているかどうか」という構造的部分型的なものではなく、
「Personの#nameを持っているか」というbranded type的な評価になる
だから#hoge in objectという式のみで、そのinstanceであることを確定できる
code:ts
class Person {
constructor(name: string) {
this.#name = name;
}
hoge(other: object) {
if (#name in other) { // これでPersonであることが確定できる
const perosn = other // 型もちゃんとPersonになっている
}
}
}
Import Assertions
code:ts
import obj from "./something.json" assert { type: "json" };
Const Assertions and Default Type Arguments in JSDoc
JSDocでconst assersionと同等のことが書けるようになった
code:ts
let b = /** @type {const} */ ({ prop: "hello" });
というか、この辺もTypeScriptの責務なのかmrsekut.icon
Faster Load Time with realPathSync.native
windowsで読み込みがちょっと速くなった
New Snippet Completions
補完能力の向上
JSXのタグの属性補完をする時に、値の型を見て、
hoge="|"とするか
文字列型の場合
hoge={|}とするかを分けてくれる
数値型とかの場合
でもこれ、文字列でも変数入れることあるしな?mrsekut.icon
Better Editor Support for Unresolved Types
型が見つからなかった時のhover時にanyではなく/*unresolved*/ anyと出る
Experimental Nightly-Only ECMAScript Module Support in Node.js
betaで入れようとしたが保留になったやつか
v4.7で入るんだっけ